// SSE处理模块
class SSEHandler {
    constructor() {
        this.eventSource = null;
        this.onMessageCallback = null;
        this.onDoneCallback = null;
        this.onErrorCallback = null;
    }
    
    connect(conversationId, onMessage, onDone, onError) {
        this.disconnect();
        
        this.onMessageCallback = onMessage;
        this.onDoneCallback = onDone;
        this.onErrorCallback = onError;
        
        this.eventSource = new EventSource(`/api/conversations/${conversationId}/messages`);
        
        this.eventSource.onmessage = (event) => {
            if (event.data === '[DONE]') {
                if (this.onDoneCallback) this.onDoneCallback();
                this.disconnect();
                return;
            }
            
            try {
                const data = JSON.parse(event.data);
                if (this.onMessageCallback) this.onMessageCallback(data);
            } catch (error) {
                console.error('Error parsing SSE data:', error);
            }
        };
        
        this.eventSource.onerror = (error) => {
            console.error('SSE error:', error);
            if (this.onErrorCallback) this.onErrorCallback(error);
            this.disconnect();
        };
    }
    
    disconnect() {
        if (this.eventSource) {
            this.eventSource.close();
            this.eventSource = null;
        }
    }
    
    isConnected() {
        return this.eventSource !== null;
    }
}

// 创建全局SSE处理器实例
window.sseHandler = new SSEHandler();